package com.wsc.personalblog.service.impl;

import com.alibaba.fastjson.JSON;
import com.wsc.personalblog.common.Constant;
import com.wsc.personalblog.config.RabbitMQConfig;
import com.wsc.personalblog.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class MailService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 给前端输入的邮箱，发送验证码
     * @param email
     * @return
     */
    public void sendMimeMail( String email) {
        try {
            log.info("发送验证码到"+email);
            // 生成随机数
            String code = randomCode();
            // 将随机数放置到redis中保存五分钟，直到被消费。
            String key = Constant.VERIFICATION_CODE +email;
            redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
            HashMap<String, Object> map = new HashMap<>();
            map.put("email",email);
            map.put("code",code);
            // 验证码以JSON形式发送到消息队列，异步的发送验证码给用户
            rabbitTemplate.convertAndSend(RabbitMQConfig.TOPIC_EXCHANGE, RabbitMQConfig.N_Q_ROUTING_KEY, JSON.toJSONString(map));
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("验证码获取失败");
        }
    }
    public boolean checkVCode(String mailBox ,String vCode){
        String trueVCode = (String)redisTemplate.opsForValue().get(Constant.VERIFICATION_CODE + mailBox);
        log.info("真实验证码："+trueVCode+"\t需要效验的验证码："+vCode);
        if(trueVCode == null || trueVCode.length() == 0) return false;
        if(!trueVCode.equals(vCode)) return false;
        return true;
    }
    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    private String randomCode(){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
